package com.rlax.web.base;

import java.util.Date;

import com.jfinal.ext2.core.ControllerExt;
import com.jfinal.ext2.kit.DateTimeKit;
import com.jfinal.kit.StrKit;
import com.rlax.framework.common.Consts;
import com.rlax.web.model.User;

/**
 * 控制器基类
 * @author Rlax
 *
 */
public abstract class BaseController extends ControllerExt {
	
	protected void setMessage(String message, String type, boolean isSession) {
		if (StrKit.isBlank(message) || StrKit.isBlank(type)) {
			return;
		}
		MessageBean msgbean = new MessageBean();
		msgbean.setMsg(message);
		msgbean.setType(type);
		
		if (isSession) {
			setSessionAttr(Consts.SESSION_MESSAGE, msgbean);
		} else {
			setAttr(Consts.SESSION_MESSAGE, msgbean);
		}
	}

	/**
	 * 设置提示 session 适用于 redirect 情况
	 * @param message
	 */
	protected void setSessionMessage(MessageBean message) {
		setMessage(message.getMsg(), message.getType(), true);
	}

	/**
	 * 设置提示
	 * @param message
	 */
	protected void setMessage(MessageBean message) {
		setMessage(message.getMsg(), message.getType(), false);
	}
	
	protected void getSessionMessage() {
		MessageBean message = getSessionAttr(Consts.SESSION_MESSAGE);
		if (message != null) {
			removeSessionAttr(Consts.SESSION_MESSAGE);
			setMessage(message.getMsg(), message.getType(), false);
		}
	}
	
	protected void setSuccessMessage(String message) {
		setMessage(message, MessageBean.SUCCESS_TYPE, false);
	}
	
	protected void setErrorMessage(String message) {
		setMessage(message, MessageBean.DANGER_TYPE, false);
	}
	
	protected void setInfoMessage(String message) {
		setMessage(message, MessageBean.INFO_TYPE, false);
	}
	
	protected void setSessionSuccessMessage(String message) {
		setMessage(message, MessageBean.SUCCESS_TYPE, true);
	}
	
	protected void setSessionErrorMessage(String message) {
		setMessage(message, MessageBean.DANGER_TYPE, true);
	}

	protected void setSessionInfoMessage(String message) {
		setMessage(message, MessageBean.INFO_TYPE, true);
	}
	
	/**
	 * 获取登录用户名
	 * @return
	 */
	protected String getLoginName() {
		User user = getSessionAttr(Consts.SESSION_USER);
		if (user == null) {
			return null;
		}
		return user.getName();
	}
	
	/**
	 * 获取当前时间：2016-04-21 15:56:24
	 * @return
	 */
	protected String getDateTime() {
		return DateTimeKit.formatDateToFULL24HRStyle("-", new Date());
	}
	
	/**
	 * 获取当前日期： 默认格式 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	protected String getDateTime(String style) {
		return DateTimeKit.formatDateToStyle(style, new Date());
	}

	/**
	 * 创建token
	 */
	@Override
	public void createToken() {
		super.createToken(Consts.TOKEN_TAG);
	}

	/**
	 * 校验token
	 */
	@Override
	public boolean validateToken() {
		return super.validateToken(Consts.TOKEN_TAG);
	}
	
	
}
